package com.bart.c_actor

import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.actor.Actor.Receive

/**
  * Created by BartG on 2018/10/9.
  * 测试 actor 的消息交换
  *
  */
class ActorMessageExchange {


}

object ActorMessageExchange {

  def main(args: Array[String]): Unit = {
    // 1. 创建 actor 的 ActorSystem 单例的工厂
    val pingPong = ActorSystem("PING_PONG")

    // 2. 创建服务端的实例
    val actorServer = pingPong.actorOf(Props[MsgServer], "MsgServer")

    // 3. 创建客户端的实例,将服务端的 ref 传递进去
    val actorClient = pingPong.actorOf(Props(new MsgClient(actorServer)), "MsgClient")

    actorClient ! "start"
    actorServer ! "start"

  }

}

/**
  * 服务端
  */
class MsgServer extends Actor {

  override def receive: Receive = {
    case "start" => {
      println("服务端准备好了！")
    }
    case "PING" => {
      println("服务端接收到 PING ... ")
      Thread.sleep(1000)
      // 向发消息的一方发送消息
      sender() ! "PONG"
    }

  }
}

/**
  * 客户端构造函数中持有服务端的ActorRef引用
  * @param serverActorRef
  */
class MsgClient(val serverActorRef: ActorRef) extends Actor {
  override def receive: Receive = {
    case "start" => {
      println("客户端端准备好了！")
      // 向发服务端的一方发送消息
      serverActorRef ! "PING"
    }
    case "PONG" => {
      println("客户端接收到 PONG ... ")
      Thread.sleep(1000)
      // 向发消息的一方发送消息
      serverActorRef ! "PING"
    }

  }
}
